import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { HMI_SHEDDING_API } from "@/api/hmi/shedding.api";
import type { SheddingInfo, SheddingUpdateRequest, SheddingUpdateResponse } from "@/api/hmi/shedding.api";

/**
 * 稳控切负荷 Store
 */
export const useSheddingStore = defineStore("shedding", () => {
  // 响应式状态
  const sheddingInfo = ref<SheddingInfo>({
    shedding_name: "",
    shedding_value: 0,
    shedding_min: 0,
    shedding_max: 0,
    shedding_enable: false,
    recover_name: "",
    recover_value: 0,
    recover_min: 0,
    recover_max: 0,
    recover_enable: false,
  });
  
  const isLoading = ref<boolean>(false);
  const isUpdating = ref<boolean>(false);
  const isReady = ref<boolean>(false);
  const lastUpdateResult = ref<SheddingUpdateResponse | null>(null);

  // 获取当前切负荷信息
  const getCurrentSheddingInfo = () => {
    return sheddingInfo.value;
  };

  // 获取切负荷层级值
  const getSheddingValue = () => {
    return sheddingInfo.value.shedding_value;
  };

  // 获取恢复负荷层级值
  const getRecoverValue = () => {
    return sheddingInfo.value.recover_value;
  };

  // 设置切负荷信息
  const setSheddingInfo = (info: SheddingInfo) => {
    sheddingInfo.value = { ...info };
    isReady.value = true;
  };

  // 重置状态
  const resetSheddingState = () => {
    sheddingInfo.value = {
      shedding_name: "",
      shedding_value: 0,
      shedding_min: 0,
      shedding_max: 0,
      shedding_enable: false,
      recover_name: "",
      recover_value: 0,
      recover_min: 0,
      recover_max: 0,
      recover_enable: false,
    };
    isLoading.value = false;
    isUpdating.value = false;
    isReady.value = false;
    lastUpdateResult.value = null;
  };

  // 验证切负荷层级值
  const validateSheddingValue = (value: number) => {
    const errors: string[] = [];
    
    if (value < sheddingInfo.value.shedding_min) {
      errors.push(`切负荷层级值不能小于 ${sheddingInfo.value.shedding_min}`);
    }
    
    if (value > sheddingInfo.value.shedding_max) {
      errors.push(`切负荷层级值不能大于 ${sheddingInfo.value.shedding_max}`);
    }
    
    return {
      isValid: errors.length === 0,
      errors,
    };
  };

  // 验证恢复负荷层级值
  const validateRecoverValue = (value: number) => {
    const errors: string[] = [];
    
    if (value < sheddingInfo.value.recover_min) {
      errors.push(`恢复负荷层级值不能小于 ${sheddingInfo.value.recover_min}`);
    }
    
    if (value > sheddingInfo.value.recover_max) {
      errors.push(`恢复负荷层级值不能大于 ${sheddingInfo.value.recover_max}`);
    }
    
    return {
      isValid: errors.length === 0,
      errors,
    };
  };

  /**
   * 获取切负荷信息
   * @param cpu CPU 编号
   * @returns Promise<SheddingInfo>
   */
  const fetchSheddingInfo = (cpu: number = 1) => {
    return new Promise<SheddingInfo>((resolve, reject) => {
      isLoading.value = true;

      HMI_SHEDDING_API.fetchSheddingInfo(cpu)
        .then((res) => {
          setSheddingInfo(res);
          resolve(res);
        })
        .catch((error) => {
          console.error("fetchSheddingInfo error:", error);
          reject(error);
        })
        .finally(() => {
          isLoading.value = false;
        });
    });
  };

  /**
   * 更新切负荷层级
   * @param cpu CPU 编号
   * @param type 类型 (0: 切负荷层级, 1: 恢复负荷层级)
   * @param value 层级值
   * @returns Promise<SheddingUpdateResponse>
   */
  const updateSheddingLevel = (cpu: number = 1, type: number, value: number) => {
    return new Promise<SheddingUpdateResponse>((resolve, reject) => {
      // 验证数据
      const validation = type === 0 
        ? validateSheddingValue(value) 
        : validateRecoverValue(value);
      
      if (!validation.isValid) {
        reject(new Error(validation.errors.join(", ")));
        return;
      }

      isUpdating.value = true;
      const data: SheddingUpdateRequest = { value };

      HMI_SHEDDING_API.updateSheddingLevel(cpu, type, data)
        .then((res) => {
          lastUpdateResult.value = res;
          
          // 更新本地状态
          if (res.status) {
            if (type === 0) {
              sheddingInfo.value.shedding_value = value;
            } else {
              sheddingInfo.value.recover_value = value;
            }
          }
          
          resolve(res);
        })
        .catch((error) => {
          console.error("updateSheddingLevel error:", error);
          reject(error);
        })
        .finally(() => {
          isUpdating.value = false;
        });
    });
  };

  /**
   * 重置更新结果
   */
  const resetUpdateResult = () => {
    lastUpdateResult.value = null;
  };

  return {
    // 状态
    sheddingInfo,
    isLoading,
    isUpdating,
    isReady,
    lastUpdateResult,
    
    // Getters
    getCurrentSheddingInfo,
    getSheddingValue,
    getRecoverValue,
    
    // 验证函数
    validateSheddingValue,
    validateRecoverValue,
    
    // Actions
    fetchSheddingInfo,
    updateSheddingLevel,
    setSheddingInfo,
    resetSheddingState,
    resetUpdateResult,
  };
});

// 在 setup 外部使用
export function useSheddingStoreWithOut() {
  return useSheddingStore(store);
}
